using System;
using System.Linq;
using System.Text;
using RockHopper.Common.Data;
using RockHopper.Common.Model;
using Windows.ApplicationModel;
using Windows.UI.Xaml.Controls;

namespace RockHopper.TrainingCalculator.WinRT.Controls
{
    public class RacePredictorControl : Control
    {
        private static readonly ISettingsRepository settingsRepository;
        private StackPanel panel;

        public RacePredictorControl()
        {
            DefaultStyleKey = typeof (RacePredictorControl);
        }

        static RacePredictorControl()
        {
            if (!DesignMode.DesignModeEnabled)
            {
                settingsRepository = Global.Container.Resolve<ISettingsRepository>();
            }   
        }

        protected override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            panel = (StackPanel) GetTemplateChild("RacePredictionsPanelPart");
            
            foreach (var racePrediction in settingsRepository.RacePredictions.Split(new []{';'}, StringSplitOptions.RemoveEmptyEntries))
            {
                var ctrl = RacePredictionControl.Create(RaceDistance.Create(racePrediction));
                ctrl.RemoveClick += OnRacePredictionRemoveClick;
                panel.Children.Add(ctrl);
            }

            var newCtrl = new NewRacePredictionControl();
            newCtrl.AddClick += OnRacePredictionAddClick;
            panel.Children.Add(newCtrl);
        }

        private void OnRacePredictionAddClick(object sender, EventArgs e)
        {
            var ctrl2 = (NewRacePredictionControl) sender;
            panel.Children.Remove(ctrl2);

            var ctrl = RacePredictionControl.Create(ctrl2.RaceDistance);
            ctrl.RemoveClick += OnRacePredictionRemoveClick;
            panel.Children.Add(ctrl);

            panel.Children.Add(ctrl2);

            SaveRacePredictions();
        }

        private void OnRacePredictionRemoveClick(object sender, EventArgs e)
        {
            panel.Children.Remove((RacePredictionControl)sender);
            SaveRacePredictions();
        }

        private void SaveRacePredictions()
        {
            var predictions = new StringBuilder();

            foreach (var ctrl in panel.Children)
            {
                var racePrediction = ctrl as RacePredictionControl;

                if (racePrediction == null) continue;
                var raceDistance = racePrediction.RaceDistance;

                predictions.AppendFormat("{0}:{1}", raceDistance.Distance, raceDistance.Units);

                if (raceDistance.HasDisplayOverride)
                    predictions.Append(":" + raceDistance.Display);

                if (ctrl != panel.Children.Last())
                    predictions.Append(";");
            }

            settingsRepository.RacePredictions = predictions.ToString();
        }
    }
}